﻿using System;
using System.Collections.Generic;
using System.Xml.Linq;
using Microsoft.Build.Utilities;

namespace AppConfigCodeGenerator
{
    /// <summary>
    /// App Config clean task
    /// </summary>
    public class AppConfigCleanTask : Task
    {
        /// <summary>
        /// Gets or sets the name of the file.
        /// </summary>
        /// <value>
        /// The name of the file.
        /// </value>
        public String FileName { get; set; }

        /// <summary>
        /// Executes this instance.
        /// </summary>
        /// <returns>True if the operation is a success; otherwise false.</returns>
        public override bool Execute()
        {
            bool flag = false;

            try
            {
                XDocument xdoc = XDocument.Load(this.FileName);
                XElement root = xdoc.Root;

                IEnumerable<XElement> appSettings = CodeGenerator.GetConfigSectionElements(root, "appSettings");

                foreach (XElement appSetting in appSettings)
                {
                    // Delete default attribute
                    this.DeleteAttribute(appSetting, "default");
                    
                    // Delete type attribute
                    this.DeleteAttribute(appSetting, "type");

                    // Delete separator attribute
                    this.DeleteAttribute(appSetting, "separator");
                }

                xdoc.Save(this.FileName);

                flag = true;
            }
            catch (Exception e)
            {
                Log.LogError(e.Message);
            }

            return flag;
        }

        /// <summary>
        /// Deletes the attribute.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <param name="attribute">The attribute.</param>
        private void DeleteAttribute(XElement element, String attribute)
        {
            // Delete attribute
            if (element.Attribute(attribute) != null)
            {
                element.Attribute(attribute).Remove();
            }
        }
    }
}
